import router from './index'
import api from '@/assets/fetch/api'
import store from '@/store'

let isAdd = false
// 登录验证
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    // let token = store.state.token || sessionStorage.getItem('token')
    let token = 'abc'
    let userId = sessionStorage.getItem('userId')
    api.getPermission({userId: userId}).then(res => {
      let result = res.result
      if (!isAdd) {
        store.dispatch('GenerateRoutes', result).then(() => {
          console.log(result)
          router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
        })
        store.commit('SHOW_PAGES', result)
        isAdd = true
      }
      if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
        if (token) { // 当前的token是否存在
          next()
        } else {
          next({
            path: '/login',
            query: {redirect: to.fullPath} // 将跳转的路由path作为参数，登录成功后跳转到该路由
          })
        }
      } else {
        next()
      }
    })
  }
})

export default router
